﻿<h1>Type Embedding</h1>

<p>
From the article <a href="struct.html">structs in Go</a>,
we know that a struct type can have many fields.
Each field is composed of one field name and one field type.
In fact, sometimes, a struct field can be composed of one field type name only.
The way to declare struct fields is called type embedding.
</p>

<p>
This article will explain the purpose of type embedding and all kinds of details in type embedding.
</p>

<h3>What Does Type Embedding Look Like?</h3>

<div>
Here is an example demonstrating type embedding:
<pre class="line-numbers"><code class="language-go">package main

import "net/http"

func main() {
	type P = *bool
	type M = map[int]int
	var x struct {
		string // a defined non-pointer type
		error  // a defined interface type
		*int   // a non-defined pointer type
		P      // an alias of a non-defined pointer type
		M      // an alias of a non-defined type

		http.Header // a defined map type
	}
	x.string = "Go"
	x.error = nil
	x.int = new(int)
	x.P = new(bool)
	x.M = make(M)
	x.Header = http.Header{}
}
</code></pre>

<p>
In the above example, six types are embedded in the struct type.
Each type embedding forms an embedded field.
</p>

<p>
Embedded fields are also called as anonymous fields.
However, each embedded field has a name specified implicitly.
The <a href="https://golang.org/ref/spec#Qualified_identifiers">unqualified</a> type name
of an embedded field acts as the name of the field.
For example, the names of the six embedded fields in the above examples are
<code>string</code>, <code>error</code>, <code>int</code>, <code>P</code>, <code>M</code>,
and <code>Header</code>, respectively.
</p>
</div>

<a class="anchor" id="embeddable-types"></a>
<h3>Which Types Can be Embedded?</h3>

<div>
The current Go specification (version 1.13) <a href="https://golang.org/ref/spec#Struct_types">says</a>

<blockquote style="margin-top:0px;margin-bottom:0px;">
<small>
	An embedded field must be specified as a type name <code>T</code>
	or as a pointer to a non-interface type name <code>*T</code>,
	and <code>T</code> itself may not be a pointer type.
</small>
</blockquote>

<p>
The above description is accurate before Go 1.9.
However, with the introduction of type aliases in Go 1.9,
the description <a href="https://github.com/golang/go/issues/22005">becomes a little outdated and inaccurate</a>.
For example, the description doesn't include the case of
the <code>P</code> field in the example in the last section.
</p>

Here, the article tries to provide more accurate descriptions.
<ul>
<li>
	A type name <code>T</code> can be embedded as an embedded field
	unless <code>T</code> denotes a defined pointer type or a pointer type
	which base type is either a pointer or an interface type.
</li>
<li>
	A pointer type <code>*T</code>, where <code>T</code> is a type name denoting
	the base type of the pointer type, can be embedded as an embedded field
	unless type name <code>T</code> denotes a pointer or interface type.
</li>
</ul>

<!--
Here, the article tries to provide more accurate descriptions.
<ul>
<li>
	A type name <code>T</code> can be embedded as an embedded field
	unless <code>T</code> denotes a pointer type which base type
	is either a pointer or an interface type.
</li>
<li>
	A pointer type <code>*T</code>, where <code>T</code> is a type name denoting
	the base type of the pointer type, can be embedded as an embedded field
	only if type name <code>T</code> doesn't denote a pointer or interface type.
</li>
</ul>

Or, a slight modification on the description in Go specification:

<div class="alert alert-info">
An embedded field must be specified as the form <code>T</code> or <code>*T</code>,
where T is a type name and the embedded type may not
be a pointer type whose base type is a pointer or interface type.
</div>

<p>
</p>
-->

<!--
<p>
The above rules for which types can be embedded are some over-restricted and unnecessarily complicated,
which makes it some hard to describe them clearly in brief.
It looks they are intended to avoid types without methods being embedded.
However, at the same time, they also already allow many types without methods to be embedded,
such as built-in basic types and aliases of many non-defined types.
There is <a href="https://github.com/golang/go/issues/24062">a proposal</a> trying to simplify the rules but it was declined.
The rule specified in the proposal is quite simple and doesn't do any harm:
<b>if a type can provide an unqualified name, then the type can be embedded</b>.
</p>
-->

The following lists some example types which can and can't be embedded:
<pre class="line-numbers"><code class="language-go">type Encoder interface {Encode([]byte) []byte}
type Person struct {name string; age int}
type Alias = struct {name string; age int}
type AliasPtr = *struct {name string; age int}
type IntPtr *int
type AliasPP = *IntPtr

// These types and aliases can be embedded.
Encoder
Person
*Person
Alias
*Alias
AliasPtr
int
*int

// These types and aliases can't be embedded.
AliasPP          // base type is a pointer type
*Encoder         // base type is an interface type
*AliasPtr        // base type is a pointer type
IntPtr           // defined pointer type
*IntPtr          // base type is a pointer type
*chan int        // base type is a non-defined type
struct {age int} // non-defined non-pointer type
map[string]int   // non-defined non-pointer type
[]int64          // non-defined non-pointer type
func()           // non-defined non-pointer type
</code></pre>

<p>
</p>

<p>
No two fields are allowed to have the same name in a struct,
there are no exceptions for anonymous struct fields.
By the embedded field naming rules,
a non-defined pointer type can't be embedded along with its base type
in the same struct type.
For example, <code>int</code> and <code>*int</code> can't be embedded in the same struct type.
</p>
</div>

<p>
A struct type can't embed itself or its aliases, recursively.
</p>

<p>
Generally, it is only meaningful to embed types who have fields or methods
(the following sections will explain why),
though some types without any field and method can also be embedded.
</p>

<h3>What Is the Meaningfulness of Type Embedding?</h3>

<div>
<p>
The main purpose of type embedding is to extend the functionalities of the embedded types
into the embedding type, so that we don't need to re-implement
the functionalities of the embedded types for the embedding type.
</p>

Many other object-oriented programming languages use inheritance
to achieve the same goal of type embedding.
Both mechanisms have their own
<a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">benefits and drawbacks</a>.
Here, this article will not discuss which one is better.
We should just know Go chose the type embedding mechanism,
and there is a big difference between the two:
<ul>
<li>
	If a type <code>T</code> inherits another type,
	then type <code>T</code> obtains the abilities of the other type.
	At the same time, each value of type <code>T</code> can also be
	viewed as a value of the other type.
</li>
<li>
	If a type <code>T</code> embeds another type,
	then type other type becomes a part of type <code>T</code>,
	and type <code>T</code> obtains the abilities of the other type,
	but none values of type <code>T</code> can be viewed as values of the other type.
</li>
</ul>

Here is an example to show how an embedding type extends
the functionalities of the embedded type.
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Person struct {
	Name string
	Age  int
}
func (p Person) PrintName() {
	fmt.Println("Name:", p.Name)
}
func (p *Person) SetAge(age int) {
	p.Age = age
}

type Singer struct {
	Person // extends Person by embedding it
	works  []string
}

func main() {
	var gaga = Singer{Person: Person{"Gaga", 30}}
	gaga.PrintName() // Name: Gaga
	gaga.Name = "Lady Gaga"
	(&gaga).SetAge(31)
	(&gaga).PrintName()   // Name: Lady Gaga
	fmt.Println(gaga.Age) // 31
}
</code></pre>

<p>
From the above example, it looks that, after embedding type <code>Person</code>,
the type <code>Singer</code> obtains all methods and fields of type <code>Person</code>,
and type <code>*Singer</code> obtains all methods of type <code>*Person</code>.
Are the conclusions right? The following sections will answer this question.
</p>

Please note that, a <code>Singer</code> value is not a <code>Person</code> value,
the following code doesn't compile:
<pre class="line-numbers"><code class="language-go">var gaga = Singer{}
var _ Person = gaga
</code></pre>

<p>
</p>

</div>

<h3>Does the Embedding Type Obtain the Fields and Methods of the Embedded Types?</h3>

<div>
Let's list all the fields and methods of type <code>Singer</code>
and the methods of type <code>*Singer</code>
used in the last example by using <a href="reflection.html">the reflection
functionalities</a> provided in the <code>reflect</code> standard package.

<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"reflect"
)

... // the types declared in the last example

func main() {
	t := reflect.TypeOf(Singer{}) // the Singer type
	fmt.Println(t, "has", t.NumField(), "fields:")
	for i := 0; i < t.NumField(); i++ {
		fmt.Print(" field#", i, ": ", t.Field(i).Name, "\n")
	}
	fmt.Println(t, "has", t.NumMethod(), "methods:")
	for i := 0; i < t.NumMethod(); i++ {
		fmt.Print(" method#", i, ": ", t.Method(i).Name, "\n")
	}

	pt := reflect.TypeOf(&Singer{}) // the *Singer type
	fmt.Println(pt, "has", pt.NumMethod(), "methods:")
	for i := 0; i < pt.NumMethod(); i++ {
		fmt.Print(" method#", i, ": ", pt.Method(i).Name, "\n")
	}
}
</code></pre>

The result:
<pre class="output"><code>main.Singer has 2 fields:
 field#0: Person
 field#1: works
main.Singer has 1 methods:
 method#0: PrintName
*main.Singer has 2 methods:
 method#0: PrintName
 method#1: SetAge
</code></pre>

<p>
</p>

<p>
From the result, we know that the type <code>Singer</code> really owns
a <code>PrintName</code> method, and the type <code>*Singer</code> really
owns two methods, <code>PrintName</code> and <code>SetAge</code>.
But the type <code>Singer</code>doesn't own a <code>Name</code> field.
Then why is the selector expression <code>gaga.Name</code>
legal for a <code>Singer</code> value <code>gaga</code>?
Please read the next section to get the reason.
</p>

</div>

<h3>Shorthands of Selectors</h3>

<p>
From the articles <a href="struct.html">structs in Go</a> and
<a href="method.html">methods in Go</a>, we have learned that,
for a value <code>x</code>, <code>x.y</code> is called a selector,
where <code>y</code> is either a field name or a method name.
If <code>y</code> is a field name,
then <code>x</code> must be a struct value or a struct pointer value.
A selector is an expression, which represents a value.
If the selector <code>x.y</code> denotes a field, it may also
has its own fields (if <code>x.y</code> is a struct value) and methods.
Such as <code>x.y.z</code>,
where <code>z</code> can also be either a field name or a method name.
</p>

<p>
In Go, (without considering selector colliding and
shadowing explained in a later section), <b><i>if a middle name in a selector
corresponds to an embedded field, then that name can be omitted from the selector</i></b>.
This is why embedded fields are also called anonymous fields.
</p>

<div>
For example:
<pre class="line-numbers"><code class="language-go">package main

type A struct {
	x int
}
func (a A) MethodA() {}

type B struct {
	A
}
type C struct {
	B
}

func main() {
	var c C

	// The following 4 lines are equivalent.
	_ = c.B.A.x
	_ = c.B.x
	_ = c.A.x
	_ = c.x // x is called a promoted field of type C

	// The following 4 lines are equivalent.
	c.B.A.MethodA()
	c.B.MethodA()
	c.A.MethodA()
	c.MethodA()
}
</code></pre>

<p>
This is why the expression <code>gaga.Name</code> is legal
in the example in the last section.
For it is just the shorthand of <code>gaga.Person.Name</code>.
<code>Name</code> is called a promoted field of type <code>Singer</code>.
</p>

As any embedding type must be a struct type,
and the article <a href="struct.html#use-pointer-as-struct">structs in Go</a>
has mentioned that the field of an addressable struct value
can be selected through the pointers of the struct value,
so the following code is also legal in Go.
<pre class="line-numbers"><code class="language-go">func main() {
	var c C
	pc = &c

	// The following 4 lines are equivalent.
	fmt.Println(pc.B.A.x)
	fmt.Println(pc.B.x)
	fmt.Println(pc.A.x)
	fmt.Println(pc.x)

	// The following 4 lines are equivalent.
	pc.B.A.MethodA()
	pc.B.MethodA()
	pc.A.MethodA()
	pc.MethodA()
}
</code></pre>

<p>
</p>

<p>
Similarly, the selector <code>gaga.PrintName</code> can be viewed as
a shorthand of <code>gaga.Person.PrintName</code>.
But, it is also okay if we think it is not a shorthand.
After all, the type <code>Singer</code> really has a <code>PrintName</code>
method, though the method is declared implicitly
(please read the section after next for details).
For the similar reason, the selector <code>(&amp;gaga).PrintName</code>
and <code>(&amp;gaga).SetAge</code> can also be viewed as, or not as,
shorthands of <code>(&amp;gaga.Person).PrintName</code> and
<code>(&amp;gaga.Person).SetAge</code>.
</p>

<p>
Note, we can also use the selector <code>gaga.SetAge</code>, only if
<code>gaga</code> is an addressable value of type <code>Singer</code>.
It is just syntactical sugar of <code>(&amp;gaga).SetAge</code>.
Please read <a href="method.html#call">method calls</a> for details.
</p>

<p>
In the above examples, <code>c.B.A.x</code> is called the full form
of selectors <code>c.x</code>, <code>c.B.x</code> and <code>c.A.x</code>.
Similarly, <code>c.B.A.MethodA</code> is called the full form of selectors
<code>c.MethodA</code>, <code>c.B.MethodA</code> and <code>c.A.MethodA</code>.
</p>

<p>
If every middle name in the full form of a selector corresponds to
an embedded field, then the number of middle names in the selector
is called the depth of the selector.
For example, the depth of the selector <code>c.MethodA</code> used
in an above example is <i>2</i>, for the full form of the selector is
<code>c.B.A.MethodA</code>.
</p>
</div>

<a class="anchor" id="selector-shadow-and-collide"></a>
<h3>Selector Shadowing and Colliding</h3>

<div>
For a value <code>x</code> (we should always assume it is addressable, even if it is not),
it is possible that many of its full-form
selectors have the same last item <code>y</code>
and every middle name of these selectors represents an embedded field.
For such cases,
<ul>
<li>
	only the full-form selector with the shallowest depth (assume it is the only one) can be shortened as <code>x.y</code>.
	In other words, <code>x.y</code> denotes the full-form selector with the shallowest depth.
	Other full-form selectors are <b>shadowed</b> by the one with the shallowest depth.
</li>
<li>
	if there are more than one full-form selectors with the shallowest depth,
	then none of those full-form selectors can be shortened as <code>x.y</code>.
	We say those full-form selectors with the shallowest depth are <b>colliding</b> with each other.
</li>
</ul>

<p>
If a method selector is shadowed by another method selector,
and the two corresponding method signatures are identical,
we say the first method is overridden by the other one.
</p>

For example, assume <code>A</code>, <code>B</code> and <code>C</code>
are three <a href="type-system-overview.html#non-defined-type">defined types</a>.

<pre class="line-numbers"><code class="language-go">type A struct {
	x string
}
func (A) y(int) bool {
	return false
}

type B struct {
	y bool
}
func (B) x(string) {}

type C struct {
	B
}
</code></pre>

The following code doesn't compile.
The reasons is selector <code>v1.A.x</code> collides with <code>v1.B.x</code> collide with each other,
so both of them can't be shortened to <code>v1.x</code>.
The same situation is for selector <code>v1.A.y</code> and <code>v1.B.y</code>.

<pre class="line-numbers"><code class="language-go">var v1 struct {
	A
	B
}

func f1() {
	_ = v1.x
	_ = v1.y
}
</code></pre>

<p>
</p>

The following code compiles okay.
The selector <code>v2.C.B.x</code> is shadowed by <code>v2.A.x</code>, so the
selector <code>v2.x</code> is a shortened form of <code>v2.A.x</code> actually.
For the same reason, the selector <code>v2.y</code> is a shortened form of
<code>v2.A.y</code>, not of <code>v2.C.B.y</code>.

<pre class="line-numbers"><code class="language-go">var v2 struct {
	A
	C
}

func f2() {
	fmt.Printf("%T \n", v2.x) // string
	fmt.Printf("%T \n", v2.y) // func(int) bool
}
</code></pre>

<p>
</p>



</div>

<h3>Implicit Methods for Embedding Types</h3>

<div>

<p>
As mentioned above, both of type <code>Singer</code> and
type <code>*Singer</code> have a <code>PrintName</code> method each,
and the type <code>*Singer</code> also has a <code>SetAge</code> method.
However, we never explicitly declare these methods
for the two types. Where do these methods come from?
</p>

In fact, assume a struct type <code>S</code> embeds a type <code>T</code>
and the embedding is legal,
<ul>
<li>
	for each method of the embedded type <code>T</code>,
	if the selectors to that method neither collide with nor are shadowed
	by other selectors, then compilers will implicitly declare
	a corresponding method with the same prototype
	for the embedding struct type <code>S</code>.
	And consequently, compilers will also
	<a href="method.html#implicit-pointer-methods">implicitly declare
	a corresponding method</a> for the pointer type <code>*S</code>.
</li>
<li>
	for each method of the pointer type <code>*T</code>,
	if the selectors to that method neither collide with nor are shadowed
	by other selectors, then compilers will implicitly declare
	a corresponding method with the same prototype for the pointer type <code>*S</code>.
</li>
</ul>

<p>
The above facts still hold true even if <code>*T</code> is not embeddable
(a.k.a, <code>T</code> is a pointer or interface type),
in which cases, the method set of <code>*T</code> is blank.
</p>

Simply speaking,
<ul>
<li>
	type <code>struct{T}</code> and type <code>*struct{T}</code>
	both obtain all the methods of the type denoted by <code>T</code>.
</li>
<li>
	type <code>*struct{T}</code>, type <code>struct{*T}</code>,
	and type <code>*struct{*T}</code> obtains all the methods of type <code>*T</code>.
</li>
</ul>

The following methods are implicitly declared by compilers
for type <code>Singer</code> and type <code>*Singer</code>.

<pre class="line-numbers"><code class="language-go">func (s Singer) PrintName() {
	s.Person.PrintName()
}

func (s *Singer) PrintName() {
	(*s).Person.PrintName()
}

func (s *Singer) SetAge(age int) {
	// <=> (&((*s).Person)).SetAge(age)
	(&s.Person).SetAge(age)
}
</code></pre>

<p>
</p>

<p>
From the article <a href="method.html">methods in Go</a>,
we know that we can't explicitly declare methods for non-defined struct types
and non-defined pointer types whose base types are non-defined struct types.
But through type embedding, such non-defined types can also own methods.
</p>

Here is another example to show which implicit methods are declared.
<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

type F func(int) bool
func (f F) Validate(n int) bool {
	return f(n)
}
func (f *F) Modify(f2 F) {
	*f = f2
}

type B bool
func (b B) IsTrue() bool {
	return bool(b)
}
func (pb *B) Invert() {
	*pb = !*pb
}

type I interface {
	Load()
	Save()
}

func PrintTypeMethods(t reflect.Type) {
	fmt.Println(t, "has", t.NumMethod(), "methods:")
	for i := 0; i < t.NumMethod(); i++ {
		fmt.Print(" method#", i, ": ",
				t.Method(i).Name, "\n")
	}
}

func main() {
	var s struct {
		F
		*B
		I
	}

	PrintTypeMethods(reflect.TypeOf(s))
	fmt.Println()
	PrintTypeMethods(reflect.TypeOf(&s))
}
</code></pre>

The result:
<pre class="output"><code>struct { main.F; *main.B; main.I } has 5 methods:
 method#0: Invert
 method#1: IsTrue
 method#2: Load
 method#3: Save
 method#4: Validate

*struct { main.F; *main.B; main.I } has 6 methods:
 method#0: Invert
 method#1: IsTrue
 method#2: Load
 method#3: Modify
 method#4: Save
 method#5: Validate
</code></pre>

<p>
</p>

<p>
If a struct type embeds a type which implements an interface type
(the embedded type may be the interface type itself),
then generally the struct type also implements the interface type,
exception there is a method specified by the interface type
shadowed by or colliding other methods or fields.
For example, in the above example program, both the embedding struct type and
the pointer type whose base type is the embedding struct type implement the interface type <code>I</code>.
</p>

Please note, a type will only obtain the methods of the types it embeds directly or indirectly.
For example, in the following code,
<ul>
<li>
	type <code>Age</code> has no methods, for it doesn't embed any types.
</li>
<li>
	type <code>X</code> has two methods, <code>IsOdd</code> and <code>Double</code>.
	<code>IsOdd</code> is obtained through embedding type <code>MyInt</code>.
</li>
<li>
	type <code>Y</code> has no methods, for its embedded type <code>Age</code> has not methods.
</li>
<li>
	type <code>Z</code> has only one method, <code>IsOdd</code>,
	which is obtained through embedding type <code>MyInt</code>.
	It doesn't obtain the method <code>Double</code> from type <code>X</code>,
	for it doesn't embed type <code>X</code>.
</li>
</ul>

<pre class="line-numbers"><code class="language-go">type MyInt int
func (mi MyInt) IsOdd() bool {
	return mi%2 == 1
}

type Age MyInt

type X struct {
	MyInt
}
func (x X) Double() MyInt {
	return x.MyInt + x.MyInt
}

type Y struct {
	Age
}

type Z X
</code></pre>

<p>
</p>

</div>

<h3>Interface Types Embed Interface Types</h3>

<p>
Not only can struct types embed other types, but also can interface types.
But interface types can only embed interface types.
Please read <a href="interface.html#embedding">interfaces in Go</a> for details.
</p>

<!--

<h3>Two Types Embedding Two Types Which Denote the Same Type But Have Different Names Are Two Distinct Types</h3>

<div>

For example,

<pre class="line-numbers"><code class="language-go">
</code></pre>
<p>
</p>
</div>

-->

<a class="anchor" id="dead-loop-example"></a>
<h3>An Interesting Type Embedding Example</h3>

<div>
In the end, let's view an interesting example.
The example program will dead loop and stack overflow.
If you have understood the above content and
<a href="interface.html#polymorphism">polymorphism</a> and type embedding,
it is easy to understand why it will dead loop.

<pre class="line-numbers"><code class="language-go">package main

type I interface {
	m()
}

type T struct {
	I
}

func main() {
	var t T
	var i = &t
	t.I = i
	i.m() // will call t.m(), then call i.m() again, ...
}
</code></pre>

<p>
</p>
</div>



